package com.yunji.news.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunji.news.common.Result;
import com.yunji.news.entity.Category;
import com.yunji.news.mapper.CategoryMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 管理后台-分类管理控制器
 *
 * @author yunji
 * @since 2024-11-23
 */
@RestController
@RequestMapping("/admin/categories")
@CrossOrigin
public class AdminCategoryController extends ServiceImpl<CategoryMapper, Category> {
    
    @Autowired
    private CategoryMapper categoryMapper;
    
    /**
     * 获取所有分类
     */
    @GetMapping
    public Result<List<Category>> getCategories() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(Category::getSortOrder, Category::getId);
        List<Category> categories = list(wrapper);
        return Result.success(categories);
    }
    
    /**
     * 获取分类详情
     */
    @GetMapping("/{id}")
    public Result<Category> getCategory(@PathVariable Long id) {
        Category category = getById(id);
        if (category == null) {
            return Result.error("分类不存在");
        }
        return Result.success(category);
    }
    
    /**
     * 创建分类
     */
    @PostMapping
    public Result<String> createCategory(@Valid @RequestBody Category category) {
        // 检查编码是否已存在
        Category existCategory = categoryMapper.selectByCode(category.getCode());
        if (existCategory != null) {
            return Result.error("分类编码已存在");
        }
        
        boolean success = save(category);
        if (success) {
            return Result.success("创建成功");
        }
        return Result.error("创建失败");
    }
    
    /**
     * 更新分类
     */
    @PutMapping("/{id}")
    public Result<String> updateCategory(@PathVariable Long id, @Valid @RequestBody Category category) {
        // 检查编码是否已被其他分类使用
        Category existCategory = categoryMapper.selectByCode(category.getCode());
        if (existCategory != null && !existCategory.getId().equals(id)) {
            return Result.error("分类编码已存在");
        }
        
        category.setId(id);
        boolean success = updateById(category);
        if (success) {
            return Result.success("更新成功");
        }
        return Result.error("更新失败");
    }
    
    /**
     * 删除分类
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteCategory(@PathVariable Long id) {
        // TODO: 检查分类下是否有文章，如果有则不允许删除
        
        boolean success = removeById(id);
        if (success) {
            return Result.success("删除成功");
        }
        return Result.error("删除失败");
    }
}